///////////////////////////////////////////////////////////
//  OQLMinCondition.cpp
//  Implementation of the Class OQLMinCondition
//  Created on:      23-sep-2007 21:26:36
///////////////////////////////////////////////////////////

#include "OQLMinCondition.h"
#include "ResolveDBRequest.h"
#include "EmptyDBException.h"

#ifndef ZERO
	#define ZERO 0
#endif

OQLMinCondition::OQLMinCondition(){

}



OQLMinCondition::~OQLMinCondition(){

}

ListPersistent OQLMinCondition::resolve(OQLCondition* cond){
	ListPersistent list, retorno;
//	Persistent* object = NULL;
	ResolveDBRequest res;
	std::string valor("");
	//bool flag = false;
	std::string atributo("");
		
	atributo += this->attribute[0].nombre;	
	retorno.setAtributte(atributo);
		
	if(cond == NULL)
	{
		retorno = res.resolveMin((*this));
	}
	else
	{
		ListPersistent listDelete;
		list = cond->resolve(this->table); // devuelve una lista ordenada por la condicion
		// ahora ordeno la lista por el valor a devolver el minimo
		if (list.getSize() == 0)
			return retorno;
		list.sort(atributo);
		
		for(int i = ZERO; i < list.getSize(); i++)
		{
			Persistent * current = list.getPersistent(i);
			if(current->getValor(atributo) != "")
			{
				if(valor == "")
					valor = current->getValor(atributo);
				
				if(current->getValor(atributo) == valor )
					retorno.insertSort(current);
				else
				{
					listDelete.insertSort(current);				
				}
			}
			else
			{
				listDelete.insertSort(current);				
			}
		}
		listDelete.clear();
//		object = list.getFirst();
//
//		valor = object->getValor(atributo);
//		
//		for(int i = ZERO; i < list.getSize(); i++)
//		{
//			Persistent * current = list.getPersistent(i);
//			if(current->getValor(atributo) == valor )
//				retorno.insertSort(current);
//			else
//			{
//				listDelete.insertSort(current);				
//			}
//		}
//		listDelete.clear();
	}
		
	return retorno;
}

